import { Card } from "./card.js"
export class Poker{
  cards = new Array(24)
  suits = ['红桃', '黑桃', '方片', '草花']
  constructor(){
    let index = 0
    for(let i = 0; i < this.suits.length; i++){
      for(let j = 9; j < 15; j++){
        let card = new Card(this.suits[i], j)
        this.cards[index++] = card
      }
    }
  }

  output_card(){
    let index = 0
    for(let i = 0; i < this.suits.length; i++){
      for(let j = 9; j < 15; j++){
        if(index % 6 === 0 && index !== 0){
          console.log();
        }
        process.stdout.write(this.cards[index++] + ' ')
      }
    }
  }

  shuffle_card(){
    for(let i = 0; i < this.cards.length; i++){
      let random_index = Math.floor(Math.random()*this.cards.length)
      let tmp_card = this.cards[i]
      this.cards[i] = this.cards[random_index]
      this.cards[random_index] = tmp_card
    }
  }

  get_one_hand(){
    this.shuffle_card()
    let onehand = []
    for(let i = 0; i < 5; i++){
      onehand.push(this.cards[i])
    }
    return onehand
  }

  get_special_one_hand(){
    let onehand = []
    let card = new Card('红桃', 5)
    onehand.push(card)
    card = new Card('草花', 6)
    onehand.push(card)
    card = new Card('黑桃', 8)
    onehand.push(card)
    card = new Card('方片', 8)
    onehand.push(card)
    card = new Card('黑桃', 8)
    onehand.push(card)
    return onehand
  }

  output_onehand(onehand){
    for(let card of onehand){
      process.stdout.write(card+' ')
    }
  }
get_one_card(index){
    return this.cards[index]
}
  get_type(onehand){
    let suit_set = new Set()
    let rank_set = new Set()
    let card_map = new Map()
    for(let card of onehand){
      suit_set.add(card.suit)
      rank_set.add(card.rank)
      if(card_map.has(card.rank)){
        let count = card_map.get(card.rank)
        count++
        card_map.set(card.rank, count)
      }
      else{
        card_map.set(card.rank, 1)
      }
    }
    onehand.sort((a,b)=>a.rank-b.rank)

    let isStraight = false
    let isSameColor = false
    if(suit_set.size === 1){
      isSameColor = true
      // return '同花'
    }
    if(onehand[4].rank - onehand[0].rank === 4 && rank_set.size === 5){
      isStraight = true
      // return '顺子'
    }

    if(isSameColor === true && isStraight === true){
      return '同花顺'
    }
    if(isSameColor === true){
      return '同花'
    }
    if(isStraight === true){
      return '顺子'
    }

    if(rank_set.size === 4){
      return '一对'
    }
    if(rank_set.size === 5){
      return '无对'
    }

    if(rank_set.size === 2){
      let arr = [...card_map.values()]
      if(arr.includes(4)){
        return '四条'
      }
      if(arr.includes(3)){
        return '满堂红'
      }
    }
    if(rank_set.size === 3){
      let arr = [...card_map.values()]
      if(arr.includes(3)){
        return '三条'
      }
      if(arr.includes(2)){
        return '两对'
      }
    }
  }
}

